#include "CommandManager.h"
#include "Command.h"

CommandManagerPtr CommandManager::singleton;

CommandManagerPtr CommandManager::getSingleton()
{
	if(CommandManager::singleton == nullptr)
		CommandManager::singleton = std::make_shared<CommandManager>();
	return CommandManager::singleton;
}

CommandManager::CommandManager()
{
}

CommandManager::~CommandManager()
{
}

void CommandManager::add(const CommandPtr &command)
{
	commands[command->getName()] = command;
}

const CommandPtr &CommandManager::getCommand(const std::string &command_line, std::vector<std::string> &args) const
{
	//First, we split the line into command and arguments based on whitespaces
	std::string command_name;
	int arg_begin = 0;
	int arg_end = 0;
	for(unsigned int i = 0; i < command_line.size(); i++)
	{
		if(i == 0 && command_line[0] == '\0')
			arg_end = arg_end;
		if(command_line[i] == ' ')
			arg_end = i;
		else if(i == command_line.size() - 1)
			arg_end = i+1;

		if(arg_begin == 0 && arg_end != arg_begin)
			command_name = command_line.substr(arg_begin, arg_end - arg_begin);
		else if(arg_end != arg_begin)
			args.push_back(command_line.substr(arg_begin+1, arg_end - (arg_begin+1)));

		arg_begin  = arg_end;
	}

	//Find command with command_name
	auto it = commands.find(command_name);
	if(it != commands.end())
		return it->second;
	
	//Else, if we didn't find any commands with command_name
	//check if we have any commands with an alias equal to command_name
	it = commands.begin();
	for(; it != commands.end(); ++it)
	{
		if(it->second->hasAlias(command_name))
			return it->second;
	}

	//If not, the command_name command does not exist
	return null_command;
}

const CommandPtr &CommandManager::getCommand(const std::string &command_name) const
{
	//Find command with command_name
	auto it = commands.find(command_name);
	if(it != commands.end())
		return it->second;

	//If not, the command_name command does not exist
	return null_command;
}
